↜ Back to index Introduction to Numerical Analysis 2

Solutions for Lecture 1

Exercise 3

implicit none
real a, b, c, d, x, y, t
print *, "Enter a, b and c"
read *, a, b, c

! the determinant
d = b**2 - 4 * a * c

if (d < 0.0) then
    print *, "There are no real solutions"
else if (d == 0.0) then
    print *, "One solution"
    print *, "x1 = ", -b / (2 * a)
else 
    x = (-b - sqrt(d)) / (2 * a)
    y = (-b + sqrt(d)) / (2 * a)

    if (x > y) then
        t = x
        x = y
        y = t
    end if

    print *, "Two solutions"

    print *, "x1 = ", x 
    print *, "x2 = ", y
end if

end

Exercise 4

implicit none
real a, b, c, t

print *, "Enter a, b and c"
read *, a, b, c

if (a > b) then
    ! swap a and b
    t = a
    a = b
    b = t
end if

if (b > c) then
    ! swap b and c
    t = b
    b = c
    c = t
end if

if (a > b) then
    ! swap a and b
    t = a
    a = b
    b = t
end if

print *, a, b, c

end

Exercise 5

implicit none
integer n, f, i

print *, "Enter n"
read *, n

f = 1

do i = 1,n
    f = f * i
end do

print *, "Factorial of ", n, " = ", f

end

Exercise 6

implicit none
integer a, b, n, t, i

print *, "Enter n"
read *, n

a = 0
b = 1

if (n == 0) then
    b = a
else if (n == 1) then
    ! do nothing
else 
    do i = 2,n
        t = b
        b = a + b
        a = t
    end do
end if

print *, "Fibonacci ", b

end

Exercise 7

implicit none
integer n, j, m

print *, "Enter n"
read *, n

m = 1
do j = 2, n - 1
    if (mod(n, j) == 0) then
        m = 0
        exit
    end if
end do

if (m == 1) then
    print *, "yes"
else
    print *, "no"
end if
end
        
implicit none
integer n, i, j, m

print *, "Enter n"
read *, n

do i = 2, n
    m = 1
    do j = 2, i - 1
        if (mod(i, j) == 0) then
            m = 0
            exit
        end if
    end do

    if (m > 0) then
        print *, i
    end if
end do

end
implicit none
integer n, k, j, m

print *, "Enter n"
read *, n

k = 2
do while (n > 0)
    m = 1
    do j = 2, k - 1
        if (mod(k, j) == 0) then
            m = 0
            exit
        end if
    end do

    if (m > 0) then
        print *, k
        n = n - 1
    end if
    k = k + 1
end do

end
        
implicit none
integer, parameter :: n = 1000
integer sieve(2:n)
integer i, k

do i = 2, n 
    sieve(i) = 1    ! 1 indicates that i is a prime
end do

do i = 2, n
    if (sieve(i) == 1) then
        print *, i
        do k = 2, n / i
            sieve(k * i) = 0    ! multiples of i are not primes
        end do
    end if
end do

end